package server;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.sql.SQLException;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.text.View;

import common.LoginDetails;



public class Server extends Thread {

	public static String marketName = "Marketplace";
	  public Server(String[] args) {
	  
	    try {
	    	
	    	
	    	Marketplace mp = new MarketplaceImpl();
	    	new MarketGUI(mp).setVisible(true);

	    	// Register the newly created object at rmi registry.
	    	Naming.rebind(marketName, mp);
	    	System.out.println("Marketplace is ready.");
	    } catch (Exception e) {
	      System.out.println(e);
	    }
	  }
	  public void run () {
	    // Wait for incoming requests
	    try {
	      while (true) {
	        try {
	          sleep(10);
	        }   catch (InterruptedException e) { }
	      }
	    } catch (Exception e) {
	      System.out.println(e);
	    }
	  }
	  public static void main(String[] args) {
	    new Server(args).run();
	  }
	  
	  private class MarketGUI extends JFrame
	  {
		  Marketplace mp;
		  public MarketGUI(Marketplace  m)
		  {
			  this.mp = m;
			  JLabel label = new JLabel("Marketplace Server");
			  this.add(label);
			  setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
				addWindowListener(new WindowAdapter(){

					@Override
					public void windowClosing(WindowEvent arg0) {
						System.out.println("Shutdown clicked");
						try {
							mp.shutdownMarketplace();
						} catch (RemoteException | SQLException e) {
							e.printStackTrace();
						}
					}


					
				});
				setBounds(100, 100, 140, 100);
		  }
	  }
	}